package com.falling.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.falling.reggie.common.BaseContext;
import com.falling.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    // 路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        // 不需要检测登录状态的url
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMail",
                "/user/login"
        };

        boolean match = checkURL(urls, requestURI);
        // 进入if的是不需要检测的，放过
        if (match){
            filterChain.doFilter(request, response);
            return ;
        }
        // 进入if的是已登录的，放过（PC端）
        Long empId = (Long) request.getSession().getAttribute("employee");
        if (empId != null){
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request, response);
            return ;
        }

        // 进入if的是已登录的，放过（移动端）
        Long userId = (Long)request.getSession().getAttribute("user");
        if (userId != null){
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return ;
        }

        // 需要检测登录且未登录的
        // 在js中已配置跳转
        // log.info("未登录! uri {}", request.getRequestURI());
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    public boolean checkURL(String[] urls, String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) return true;
        }
        return false;
    }
}
